package com.pet.system.service.impl;

import com.pet.common.core.domain.AjaxResult;
import com.pet.common.utils.DateUtils;
import com.pet.system.domain.PetBrand;
import com.pet.system.domain.PetCart;
import com.pet.system.domain.PetProduct;
import com.pet.system.mapper.PetBrandMapper;
import com.pet.system.mapper.PetCartMapper;
import com.pet.system.mapper.PetProductMapper;
import com.pet.system.service.IPetProductService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 产品Service业务层处理
 *
 * @author pet
 * @date 2022-10-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PetProductServiceImpl implements IPetProductService {
    @Autowired
    private PetProductMapper petProductMapper;

    @Autowired
    private PetBrandMapper petBrandMapper;

    @Autowired
    private PetCartMapper petCartMapper;

    /**
     * 查询产品
     *
     * @param id 产品主键
     * @return 产品
     */
    @Override
    public PetProduct selectPetProductById(Long id) {
        return petProductMapper.selectPetProductById(id);
    }

    /**
     * 查询产品列表
     *
     * @param petProduct 产品
     * @return 产品
     */
    @Override
    public List<PetProduct> selectPetProductList(PetProduct petProduct) {
        return petProductMapper.selectPetProductList(petProduct);
    }

    /**
     * 新增产品
     *
     * @param petProduct 产品
     * @return 结果
     */
    @Override
    public int insertPetProduct(PetProduct petProduct) {
        List<String> categoryList = petBrandMapper.selectPetBrandCategoryList(petProduct.getUserId());
        List<String> brandList = petBrandMapper.selectPetBrandCategoryBrandList(petProduct.getUserId(), null);
        if (StringUtils.isBlank(petProduct.getCategory())) {
            throw new RuntimeException("类目未填写，请重新填写后上传！");
        }
        Optional<String> categoryOptional = categoryList.stream().filter(e -> e.equals(petProduct.getCategory())).findFirst();
        if (!categoryOptional.isPresent()) {
            throw new RuntimeException("类目暂未在品牌管理中维护，请在品牌管理中维护填写后上传！");
        }
        if (StringUtils.isBlank(petProduct.getBrandName())) {
            throw new RuntimeException("品牌名称未填写，请重新填写后上传！");
        }
        Optional<String> brandNameOptional = brandList.stream().filter(e -> e.equals(petProduct.getBrandName())).findFirst();
        if (!brandNameOptional.isPresent()) {
            throw new RuntimeException("品牌名称暂未在品牌管理中维护，请在品牌管理中维护填写后上传！");
        }
        PetProduct petProductParam = new PetProduct();
        petProductParam.setCategory(petProduct.getCategory());
        petProductParam.setBrandName(petProduct.getBrandName());
        petProductParam.setProductName(petProduct.getProductName());
        petProductParam.setSpec(petProduct.getSpec());
        petProductParam.setUserId(petProduct.getUserId());
        PetProduct petProductSelect = petProductMapper.selectPetProduct(petProductParam);
        if (ObjectUtils.isNotEmpty(petProductSelect)) {
            return 0;
        }
        return petProductMapper.insertPetProduct(petProduct);
    }

    /**
     * 修改产品
     *
     * @param petProduct 产品
     * @return 结果
     */
    @Override
    public int updatePetProduct(PetProduct petProduct) {
        return petProductMapper.updatePetProduct(petProduct);
    }

    /**
     * 修改产品
     *
     * @param petProduct 产品
     * @return 结果
     */
    @Override
    public int updatePetProductImage(PetProduct petProduct) {
        return petProductMapper.updatePetProductImage(petProduct);
    }

    /**
     * 批量删除产品
     *
     * @param ids 需要删除的产品主键
     * @return 结果
     */
    @Override
    public int deletePetProductByIds(Long[] ids) {
        return petProductMapper.deletePetProductByIds(ids);
    }

    /**
     * 删除产品信息
     *
     * @param id 产品主键
     * @return 结果
     */
    @Override
    public int deletePetProductById(Long id) {
        PetCart petCart = new PetCart();
        petCart.setProductId(id);
        List<PetCart> petCartList = petCartMapper.selectPetCartList(petCart);
        if (CollectionUtils.isNotEmpty(petCartList)) {
            //先删除
            petCartList.forEach(e -> petCartMapper.deletePetCartById(e.getId()));
        }
        return petProductMapper.deletePetProductById(id);
    }

    @Override
    @Transactional
    public AjaxResult importProduct(List<PetProduct> productList, Long userId) {
        List<String> categoryList = petBrandMapper.selectPetBrandCategoryList(userId);
        List<String> brandList = petBrandMapper.selectPetBrandCategoryBrandList(userId, null);
        try {
            for (int i = 0; i < productList.size(); i++) {
                PetProduct petProduct = productList.get(i);
                if (StringUtils.isBlank(petProduct.getCategory())) {
                    throw new RuntimeException("第" + (i + 1) + "行数据的类目未填写，请重新填写后上传！");
                }
                Optional<String> categoryOptional = categoryList.stream().filter(e -> e.equals(petProduct.getCategory())).findFirst();
                if (!categoryOptional.isPresent()) {
                    throw new RuntimeException("第" + (i + 1) + "行数据的类目:" + petProduct.getCategory() + "暂未在品牌管理中维护，请在品牌管理中维护填写后上传！");
                }
                if (StringUtils.isBlank(petProduct.getBrandName())) {
                    throw new RuntimeException("第" + (i + 1) + "行数据的品牌未填写，请重新填写后上传！");
                }
                if (petProduct.getBrandName().length() > 4) {
                    throw new RuntimeException("第" + (i + 1) + "行数据的品牌大于4个字，请重新填写后上传！");
                }
                Optional<String> brandNameOptional = brandList.stream().filter(e -> e.equals(petProduct.getBrandName())).findFirst();
                if (!brandNameOptional.isPresent()) {
                    throw new RuntimeException("第" + (i + 1) + "行数据的品牌:" + petProduct.getBrandName() + "暂未在品牌管理中维护，请在品牌管理中维护填写后上传！");
                }
                if (StringUtils.isBlank(petProduct.getProductName())) {
                    throw new RuntimeException("第" + (i + 1) + "行数据的产品名称未填写，请重新填写后上传！");
                }
                if (StringUtils.isBlank(petProduct.getSpec())) {
                    throw new RuntimeException("第" + (i + 1) + "行数据的规格未填写，请重新填写后上传！");
                }
                if (StringUtils.isNotBlank(petProduct.getPromotion()) && petProduct.getPromotion().length() > 12) {
                    throw new RuntimeException("第" + (i + 1) + "行数据的优惠活动大于12个字，请重新填写后上传！");
                }

                PetProduct petProductParam = new PetProduct();
                petProductParam.setCategory(petProduct.getCategory());
                petProductParam.setBrandName(petProduct.getBrandName());
                petProductParam.setProductName(petProduct.getProductName());
                petProductParam.setSpec(petProduct.getSpec());
                petProductParam.setUserId(userId);

                PetBrand petBrandParam = new PetBrand();
                petBrandParam.setCategory(petProduct.getCategory());
                petBrandParam.setBrandName(petProduct.getBrandName());
                petBrandParam.setUserId(userId);
                PetBrand petBrand = petBrandMapper.selectPetBrandByEntity(petBrandParam);
                if (ObjectUtils.isEmpty(petBrand) || null == petBrand.getId()) {
                    throw new RuntimeException("第" + (i + 1) + "行数据未查到品牌信息，请重新填写后上传！");
                }

                PetProduct petProductSelect = petProductMapper.selectPetProduct(petProductParam);
                if (ObjectUtils.isEmpty(petProductSelect)) {
                    //新增
                    petProduct.setBrandId(petBrand.getId());
                    petProductMapper.insertPetProduct(petProduct);
                } else {
                    //更新
                    petProductSelect.setTradePrice(petProduct.getTradePrice());
                    petProductSelect.setRetailPrice(petProduct.getRetailPrice());
                    petProductSelect.setPromotion(petProduct.getPromotion());
                    petProductMapper.updatePetProduct(petProductSelect);
                }
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }
}
